package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.local.UserContext;
import com.leyou.common.dto.SkuDTO;
import com.leyou.common.exception.LyException;
import com.leyou.dto.AddressDTO;
import com.leyou.item.client.ItemClient;
import com.leyou.trade.dto.OrderFormDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.entity.enums.OrderStatus;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderDetailService;
import com.leyou.trade.service.OrderLogisticsService;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import feign.FeignException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderLogisticsService logisticsService;

    @Autowired
    private UserClient userClient;

    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderDTO) {
        //1. 新增订单
        Order order = new Order();
        //1.1 金额相关数据
        Map<Long, Integer> carts = orderDTO.getCarts();
        //1) 获取商品id
        Set<Long> skuIds = carts.keySet();
        List<SkuDTO> skuDTOList = itemClient.querySkuByIds(skuIds);
        //2)计算商品总金额
        long total = 0L;

        for (SkuDTO skuDTO : skuDTOList) {
            //获取商品购买的数量
            Integer num = carts.get(skuDTO.getId());
            //总金额
            total += skuDTO.getPrice() * num;

          if(!skuDTO.getSaleable()){
                throw new LyException(500,"商品已经下架,无法下单");
            }
        }
        order.setTotalFee(total);
        order.setPostFee(0L);
        order.setActualFee(order.getTotalFee() - order.getPostFee()/*减去优惠金额*/);
        order.setPaymentType(orderDTO.getPaymentType());

        //1.2.用户信息
        Long userId = UserContext.getUser().getId();
        order.setUserId(userId);
        //1.3.状态
        order.setStatus(OrderStatus.INIT.getValue());
        //1.4.写入数据库
        boolean success = save(order);
        if (!success) {
            throw new LyException(500, "订单新增失败");
        }
        //1.5.id回显
        Long orderId = order.getOrderId();

        //2.新增订单详情
        //2.1定义detail的集合,用以封装orderDetail
        ArrayList<OrderDetail> details = new ArrayList<>();
        //2.2 遍历skudto
        for (SkuDTO skuDTO : skuDTOList) {
            //获取商品购买的数量
            Integer num = carts.get(skuDTO.getId());
            //封装detail
            details.add(transferDetail(skuDTO, num, orderId));
        }
        //2.3 批量处理
        orderDetailService.saveBatch(details);

        //3.新增订单物流
        //3.1获取addressId
        Long addressId = orderDTO.getAddressId();
        //3.2 在userService服务中根据id获取地址信息
        AddressDTO addressDTO = null;
        try {
            addressDTO = userClient.queryAddressById(addressId);
        } catch (FeignException e) {
           throw  new LyException(e.status(),e.contentUTF8());
        }
        if (!userId.equals(addressDTO.getUserId())) {
            throw new LyException(400, "请求参数有误");
        }
        //3.2 把信息封装到物流表中OrderLogistics
        OrderLogistics orderLogistics = addressDTO.toEntity(OrderLogistics.class);
        orderLogistics.setOrderId(orderId);
        success = logisticsService.save(orderLogistics);
        if (!success) {
            throw new LyException(500, "订单新增失败");
        }
        try {
            //4.扣减库存
            itemClient.deductStock(carts);
        } catch (FeignException e) {
          throw  new LyException(e.status(),e.contentUTF8());
        }


        return orderId;
    }

    private OrderDetail transferDetail(SkuDTO skuDTO, Integer num, Long orderId) {
        OrderDetail detail = new OrderDetail();
        detail.setTitle(skuDTO.getTitle());
        detail.setSpec(skuDTO.getSpecialSpec());
        detail.setSkuId(skuDTO.getId());
        detail.setPrice(skuDTO.getPrice());
        detail.setOrderId(orderId);
        detail.setNum(num);
        detail.setImage(StringUtils.substringBefore(skuDTO.getImages(), ","));
        return detail;
    }
}